<?php

namespace backend\controllers;


use common\models\CosModel;
use common\models\FileModel;
use yii\web\Controller;
use yii\web\UploadedFile;

class FileController extends Controller
{

    public $enableCsrfValidation = false;


    public function actions()
    {
        return [
            'uedit-upload' => [
                'class'  => 'kucha\ueditor\UEditorAction',
                'config' => [
                    "imageUrlPrefix"  => \Yii::$app->params['cos']['prefix'],//图片访问路径前缀
                    "imagePathFormat" => "/upload/ueditor/{yyyy}{mm}{dd}/{time}{rand:6}", //上传保存路径
                    "videoUrlPrefix"  => \Yii::$app->params['cos']['prefix'],//视频访问路径前缀
                ],
            ]
        ];
    }


    public function actionUpload()
    {
        \Yii::$app->response->format = 'json';
        \Yii::$app->response->getHeaders()->set('Access-Control-Allow-Origin',"*");
        if (\Yii::$app->request->isPost) {
            $model = new FileModel();
            $model->file = UploadedFile::getInstanceByName('file');
            try{
                $res = $model->upload();
                return [
                    'code' => 0,
                    'url'  => $res['url'],
                    'attachment'  => $res['url'],
                ];
            }catch (\Exception  $e) {
                return [
                    'code' => 1,
                    'msg'  => $e->getMessage()
                ];
            }
        }else{
            return [
                'code' => 1,
                'msg'  => '未知错误'
            ];
        }
    }
}